#include "KEY.h"
#include "Bitband.h"

void KEY_Init(void)
{
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOE,ENABLE);
	GPIO_InitTypeDef GPIO_InitStruct;
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN;
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0;
	GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_InitStruct.GPIO_Speed = GPIO_High_Speed;
	GPIO_Init(GPIOA, &GPIO_InitStruct);
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4;
	GPIO_Init(GPIOE, &GPIO_InitStruct);
}

void KEY_EXTI_Init(void)
{
	EXTI_InitTypeDef EXTI_InitStruct;
	NVIC_InitTypeDef NVIC_InitStruct;
	
	KEY_Init();
	/*SYSCFG配置*/
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
	SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSource0);
	SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOE, EXTI_PinSource2);
	SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOE, EXTI_PinSource3);
	SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOE, EXTI_PinSource4);
	/*EXTI外部中断配置*/
	EXTI_InitStruct.EXTI_Line = EXTI_Line0|EXTI_Line2|EXTI_Line3|EXTI_Line4;
	EXTI_InitStruct.EXTI_LineCmd = ENABLE;
	EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Falling;
	EXTI_Init(&EXTI_InitStruct);
	/*NVIC配置*/
	NVIC_InitStruct.NVIC_IRQChannel = EXTI0_IRQn;
	NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 2;
	NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;
	NVIC_Init(&NVIC_InitStruct);
	NVIC_InitStruct.NVIC_IRQChannel = EXTI2_IRQn;
	NVIC_Init(&NVIC_InitStruct);
	NVIC_InitStruct.NVIC_IRQChannel = EXTI3_IRQn;
	NVIC_Init(&NVIC_InitStruct);
	NVIC_InitStruct.NVIC_IRQChannel = EXTI4_IRQn;
	NVIC_Init(&NVIC_InitStruct);
}

uint8_t KEY_Get_Num(void)
{
	uint8_t Key_Num = 0;
	if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0)
	{
		Delay_ms(15);
		while(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0);
		Delay_ms(15);
		Key_Num = 1;
	}
	if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_2) == 0)
	{
		Delay_ms(15);
		while(GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_2) == 0);
		Delay_ms(15);
		Key_Num = 2;
	}
	if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_3) == 0)
	{
		Delay_ms(15);
		while(GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_3) == 0);
		Delay_ms(15);
		Key_Num = 3;
	}
	if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_4) == 0)
	{
		Delay_ms(15);
		while(GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_4) == 0);
		Delay_ms(15);
		Key_Num = 4;
	}
	return Key_Num;
}

int KEY_Get_State(int key_num)
{
	switch(key_num)
	{
		case KEY0:
			//return GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0);
			return PAin(0);
		case KEY1:
			//return GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_2);
			return PEin(2);
		case KEY2:
			//return GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_3);
			return PEin(3);
		case KEY3:
			//return GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_4);
			return PEin(4);
		default:
			return -1;
	}
}



